package com.wzh.navcode.strategy;

import com.wzh.navcode.domain.entity.HotData;
import com.wzh.navcode.domain.vo.WeiBoHotTopic;
import com.wzh.navcode.mapstruct.WeiBoHotTopicMapstruct;
import com.wzh.navcode.service.CrawlStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangzhenghai
 * description: 微博热搜数据采集策略
 */
@Service("weiboStrategy")
@Slf4j
public class WeiboCrawlStrategy implements CrawlStrategy {

    @Override
    public List<HotData> crawl() {
        List<WeiBoHotTopic> hotTopics = new ArrayList<>();
        try {
            // 设置请求头，模拟浏览器访问
            Document doc = Jsoup.connect("https://s.weibo.com/top/summary?cate=realtimehot")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .header("Cookie", "SUB=_2AkMQCt28f8NxqwFRmf4Qy27ma41yyAvEieKmVixnJRMxHRl-yT9yql0otRB6O4rzU9CN6B7VNjUj20ydp-rw9FgVE4UL; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WF2JxUgKpSS5mCgoAloyn0j; SINAGLOBAL=6244590812470.905.1733710476356; _s_tentry=link.csdn.net; Apache=6507348153905.686.1733795051773; ULV=1733795051776:2:2:2:6507348153905.686.1733795051773:1733710476401; XSRF-TOKEN=tWDZfUGHlfKkTL5sGqxB5qn5; WBPSESS=UpRpmiZuabnjxMaPsrZiV4X4itYZg5ch7uCLdFEBDBfOLvGKst_e1obHwFlGgKhlhIt8vwSJmUhF7wexKEG4m_3Jvex1HO6XaJgARAn3tDCYcebTQZCef7HGUmHKp-h0zO_4pjZXiciIIfmowJX5fi5c0zm5UdktE-CLr-0v9O0=; UOR=,,www.google.com.hk")
                    .get();
            Elements tableRows = doc.select("table tbody tr");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            String formattedTime = LocalDateTime.now().format(formatter);
            for (Element row : tableRows) {
                String title = row.select("td.td-02 a").text();
                String hot = row.select("td.td-02 span").text();
                String url = "https://s.weibo.com" + row.select("td.td-02 a").attr("href");
                String date = "今天" + formattedTime;
                if (!title.isEmpty()) {
                    hotTopics.add(new WeiBoHotTopic(title, hot, url, date));
                }
            }
        } catch (IOException e) {
            log.error("微博热搜数据采集失败", e);
        }
        List<HotData> hotDataList = new ArrayList<>();
        hotTopics.forEach(weiBoHotTopic -> {
            if (StringUtils.isEmpty(weiBoHotTopic.getHot())) {
                weiBoHotTopic.setHot("↑");
            }
            hotDataList.add(WeiBoHotTopicMapstruct.INSTANCE.weiBoHotTopicMapstruct(weiBoHotTopic));
        });
        return hotDataList.subList(1, 11);
    }
}